import router from "./router";
import store from "./store";
import STATUS from "@/enum/STATUS.js";
import { tileNestingData, getDataInArray } from "@/assets/js/util.js";
import { getFunctionList } from "@/api/authority.js";
import { baseRouter } from "./router/baseRouter.js";

import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import _ from "lodash";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

// 联营渠道路由，需要默认配置
const unionFrontRouter = [
  { frontRoute: "ally" },
  { frontRoute: "ally_list" },
  { frontRoute: "ally_create" },
  { frontRoute: "ally_detail" },
  { frontRoute: "ally_edit" },
  { frontRoute: "ally_delete" },
  { frontRoute: "ally_import" },
  { frontRoute: "ally_actorStatusChange" },
  { frontRoute: "ally_liveDetail" },
  { frontRoute: "ally_addLive" },
  { frontRoute: "ally_editLive" },
  { frontRoute: "ally_deleteLive" }
];
// const unionFrontRouter = [];

const whiteList = ["/login", "/auth-redirect"]; // no redirect whitelist
router.beforeEach(async (to, from, next) => {
  // 应该是有了缓存后，链接带上了参数导致侧边栏点击自己也会加载且加载有问题，所以点击自己禁止
  if (to.path == from.path) {
    return;
  }

  // start progress bar
  NProgress.start();

  // 如果是跳转到这里，那么重置sid的token，不然用以前会提示过期导致出问题
  if (to.query.token) {
    const sid = { access_token: to.query.token };
    localStorage.setItem("sid", JSON.stringify(sid));
    store.commit("setSid", sid);

    // store.commit("setSid", sid);
  }

  // set page title
  document.title = getPageTitle(to.meta.title);

  // determine whether the user has logged in
  // const hasToken = getToken()

  // 判断是否登陆
  if (store.state.sid && store.state.sid.access_token) {
    // 判断当前用户是否已拉取拉取用户信息
    if (!store.state.userData) {
      try {
        // get user info
        // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
        store.dispatch("user/getInfo").then(userResp => {
          const userRespData = userResp || {};
          if (userRespData.code === STATUS.success[0]) {
            // 获取平台
            // store.dispatch("getSkillList", { latest: true });
            store.dispatch("getPlatformList", { latest: true });

            localStorage.setItem("userData", JSON.stringify(userRespData.data));
            const corporations = userRespData.data.corporations || [];
            store.commit("setUserData", userRespData.data);
            // 如果当前公司不存在，默认第一个
            // let currentCorporationId = localStorage.getItem("currentCorporationId");
            let localCurrentCorporation = localStorage.getItem(
              "currentCorporation"
            );
            let currentCorporation =
              localCurrentCorporation && localCurrentCorporation != "undefined"
                ? JSON.parse(localCurrentCorporation)
                : {};
            // let currentCorporation = JSON.parse(
            //   localStorage.getItem("currentCorporation") || "{}"
            // );

            // let currentCorporation;
            const arrCorporations = tileNestingData(_.cloneDeep(corporations));
            if (!currentCorporation || !currentCorporation.id) {
              currentCorporation = arrCorporations[0] || {
                id: userRespData.data.tenantId
              };
            } else {
              // 不在当前权限公司，那么默认第一个
              const newData = getDataInArray(
                arrCorporations,
                currentCorporation.id
              );
              if (!newData) {
                if (arrCorporations.length) {
                  currentCorporation = arrCorporations[0];
                } else {
                  currentCorporation = { id: userRespData.data.tenantId };
                }
              }
              // if (!newData && arrCorporations.length) {
              //   currentCorporation = arrCorporations[0];
              //   // newCurrentCorporationId = corporations[0].id;
              // } else {
              //   currentCorporation = { id: userRespData.data.tenantId };
              // }
            }

            // 设置当前公司id
            localStorage.setItem(
              "currentCorporation",
              JSON.stringify(currentCorporation)
            );
            store.commit("setAllCorporationTile", arrCorporations);
            store.commit("setCurrentCorporation", currentCorporation);
            // localStorage.setItem("currentCorporation", newCurrentCorporationId);
            // 获取当前公司的
            // let currentC = getDataInArray(arrCorporations, currentCorporationId)
            getFunctionList().then(fnResp => {
              const fnRespData = fnResp.data || {};
              if (fnRespData.code === STATUS.success[0]) {
                let frontRoute = fnRespData.data;
                if (store.state.userData.channelType == "union") {
                  frontRoute = frontRoute.concat(unionFrontRouter);
                }

                store.commit("setFrontRoute", frontRoute);
                store.commit("setFromRoute", from);
                // let createdRouter;
                // 是管理员，直接返回全部页面
                // if (userRespData.data.roleName.indexOf("管理员") >= 0) {
                //   createdRouter = _.cloneDeep(authorityRouter);
                // } else {
                //   createdRouter = getRouters(
                //     store.state.frontRoute,
                //     _.cloneDeep(authorityRouter)
                //   );
                // }
                // let authorityRouterDeep = _.cloneDeep(authorityRouter);
                // authorityRouterDeep.map((item) => {
                //   let fn;
                //   if (item.meta && item.meta.fn) {
                //     if (item.children) {
                //       fn = getChildrenFn(item.children);
                //     } else {
                //       fn = item.fn;
                //     }
                //   }
                //   item.fn = fn;
                // });
                // const arrAuthorityRouter = _.cloneDeep(authorityRouter)

                // const newAuthorityRouter = setOffspringFn(arrAuthorityRouter)
                store
                  .dispatch("permission/generateRoutes", store.state.frontRoute)
                  .then(createdRouter => {
                    const allRouters = baseRouter.concat(createdRouter);
                    store.commit("setRoutes", allRouters);
                    router.addRoutes(createdRouter); // 动态添加可访问路由表
                    next({ ...to, replace: true });
                  });
              }
            });
          }
        });
      } catch (error) {
        // remove token and go to login page to re-login
        await store.dispatch("user/resetToken");
        Message.error(error || "Has Error");
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    } else {
      if (to.path === "/login") {
        next({ path: "/" });
        NProgress.done();
      } else {
        store.commit("setFromRoute", from);
        next(); // 当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      NProgress.done();
      // other pages that do not have permission to access are redirected to the login page.
      const url = window.location.origin;
      if (/localhost|127\.0\.0\.1/.test(url)) {
        location.href = "https://test.yj543.com/";
      } else {
        location.href = "/";
      }
      // next(`/login?redirect=${to.path}`)
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
